package com.lyy;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author Liangyaoyun
 */
public class JedisStandaloneUtil {

    /** 单机Jedis连接池的配置实例 */
    private static final JedisPoolConfig JEDIS_POOL_CONFIG;
    /** 单机Jedis超时时间 */
    private static final int TIMEOUT = 10000;
    /** 单机Jedis主机地址 */
    private static final String HOST = "192.168.159.77";
    /** 单机Jedis端口号 */
    private static final int PORT = 6379;

    static {
        // 初始化Jedis连接池的配置实例
        JEDIS_POOL_CONFIG = new JedisPoolConfig();
        // Jedis连接池最多容纳8个连接
        JEDIS_POOL_CONFIG.setMaxTotal(8);
        // Jedis连接池最大阻塞时间10s
        JEDIS_POOL_CONFIG.setMaxWaitMillis(10000);
        // Jedis连接池最大空闲8个连接
        JEDIS_POOL_CONFIG.setMaxIdle(8);
        // Jedis连接池最小空闲0个连接
        JEDIS_POOL_CONFIG.setMinIdle(0);
    }

    /**使用静态内部类保证Jedis单机连接池的单例性*/
    private static final class JedisPoolHolder {
        private static final JedisPool jedisPool
                = new JedisPool(JEDIS_POOL_CONFIG, HOST, PORT, TIMEOUT);
    }

    /**
     * 从Jedis单机连接池中获取并返回一个单机Jedis连接
     *
     * @return 一个单机Jedis连接
     */
    public static Jedis getJedis() {
        return JedisPoolHolder.jedisPool.getResource();
    }
}
